<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input v-model="userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handlerSearch"
          :disabled="userName.length > 0 ? false : true">搜索</el-button>
        <el-button type="primary" @click="handlerReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px;">
    <el-button type="primary" size="default" @click="handlerAddUser">添加用户</el-button>
    <el-button :disabled="userIds.length > 0 ? false : true" type="danger" @click="handlerBatchDelete"
      size="default">批量删除</el-button>
    <!-- table展示用户信息 -->
    <el-table :data="userAttr" border stripe style=" margin: 10px 0px; width: 100%"
      @selection-change="handlerSelectionChange">
      <el-table-column type="selection" width="55" :show-overflow-tooltip="true" />
      <el-table-column label="#" align="center" type="index" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户名字" align="center" prop="username" :show-overflow-tooltip="true" />
      <el-table-column label="用户名称" align="center" prop="nickname" :show-overflow-tooltip="true" />
      <el-table-column label="用户角色" align="center" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createdDate" :show-overflow-tooltip="true" />
      <el-table-column label="更新时间" align="center" prop="updatedDate" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button type="primary" size="mini" icon="User" @click="handlerDispatcherRole(row)">分配角色</el-button>
          <el-button type="primary" size="mini" icon="Edit" @click="handlerEdit(row)">编辑</el-button>
          <el-popconfirm class="box-item" :title="`确定删除${row.username}吗`" @confirm="handlerDelete(row)" width="200">
            <template #reference>
              <el-button type="danger" icon="Delete" size="mini">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :page-sizes="[2, 3, 5, 7, 10]"
        :background="true" layout="prev, pager, next, jumper, ->,sizes,total" :total="total"
        @size-change="handleSizeChange" @current-change="handlerUserList" />
    </el-table>
  </el-card>
  <!-- 抽屉的结构 -->
  <el-drawer v-model="drawer" direction="rtl">
    <!-- 抽屉的标题：动态变化 -->
    <template #header>
      <h4>{{ userParam.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <!-- 表单 -->
      <el-form :model="userParam" :rules="rules" :ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input v-model="userParam.username" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userParam.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="userParam.id === 0">
          <el-input type="password" v-model="userParam.password" placeholder="请输入用户密码" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="handlerSaveOrUpdateUser">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉组件:用于角色的分配 -->
  <el-drawer v-model="roleDrawer" direction="rtl">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form :model="userParam" :ref="roleFormRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input :disabled="true" v-model="userParam.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表" prop="zone">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
            全选
          </el-checkbox>
          <el-checkbox-group v-model="checkedRoleIds" @change="handleCheckedRolesChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{
              role.roleName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelRoleDispatcher">取消</el-button>
        <el-button type="primary" @click="confirmRoleDispatcher">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import type { Response } from '@/api/type';
import type { RoleInfoVO, UserRole, UserRoleList } from '@/api/acl/role/type';
import { reqAssignRole, reqGetUserRoleAndAllRoleList, reqRemoveUserByIds, reqSaveOrUpdateUser, reqUserList, reqUserListByUserName } from '@/api/acl/user';
import type { AssignRoleParam, UserList, UserVO } from '@/api/acl/user/type';
import useLayOutSettingStore from '@/store/modules/setting'
import { ElMessage } from 'element-plus';


import { ref, onMounted, reactive, nextTick } from 'vue';

let pageIndex = ref<number>(1);
let pageSize = ref<number>(10);
let total = ref<number>(0);

let userAttr = ref<UserList>([]);
let userName = ref<string>('');

let userIds = ref<number[]>([]);
// 定义一个响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
let formRef = ref<any>();

let roleDrawer = ref<boolean>(false);

let roleFormRef = ref<any>(false);


let checkAll = ref<boolean>(false);
// 设置不确定的样式 
let isIndeterminate = ref<boolean>(true);

// 目前用户已有的角色
let checkedRoleIds = ref<number[]>([]);

let allRoles = ref<UserRoleList>([]);


const settingStore = useLayOutSettingStore();
const handlerReset = () => {
  settingStore.refresh = !settingStore.refresh;
}
// 复选框勾选的时候会触发的事件
const handlerSelectionChange = (user: UserList) => {
  userIds.value = user.map(item => {
    return (item.id as number)
  })
}

const handleCheckedRolesChange = (value: string[]) => {
  const checkedAll = value.length === allRoles.value.length;
  isIndeterminate.value = !checkedAll && value.length > 0;
}
/**
 * When the user checks or unchecks the "Select All" checkbox,
 * update the checkedRoleIds state to include all role IDs if checked,
 * or an empty array if unchecked.
 * @param {boolean} checkedAll Whether the user has checked or unchecked the "Select All" checkbox.
 */
let handleCheckAllChange = (checkedAll: boolean) => {
  if (checkedAll) {
    checkedRoleIds.value = allRoles.value.map(item => item.id).filter(id => id !== undefined) as number[];
  } else {
    checkedRoleIds.value = [];
  }
  isIndeterminate.value = false;
}

const confirmRoleDispatcher = async () => {
  let param = ref<AssignRoleParam>({
    userId: userParam.id ?? 0,
    roleIds: checkedRoleIds.value
  });
  let assignRoleResult = await reqAssignRole(param.value);
  if (assignRoleResult.code != 200) {
    ElMessage.error(assignRoleResult.message);
    return;
  }
  ElMessage.success(assignRoleResult.message);
  ElMessage.success("分配角色成功");
  roleDrawer.value = false;
  handlerUserList(pageIndex.value);
}

const cancelRoleDispatcher = () => {
  roleDrawer.value = false;
  // roleFormRef.value?.resetFields();
}

// 校验用户名称
const validatorUsername = (_rule: any, value: string, callBack: any) => {
  if (value.trim().length < 6) {
    callBack(new Error('用户名长度不能小于6位'));
  } else {
    callBack();
  }

}

const validatorNickName = (_rule: any, value: string, callBack: any) => {
  if (value.trim().length < 6) {
    callBack(new Error('用户昵称长度不能小于6位'));
  } else {
    callBack();
  }
}

const validatorPassword = (_rule: any, value: string, callBack: any) => {
  if (value.trim().length < 6) {
    callBack(new Error('用户密码长度不能小于6位'));
  } else {
    callBack();
  }

}
const rules = reactive<any>({
  username: [
    { required: true, trigger: 'blur', validator: validatorUsername },
  ],
  nickName: [
    { required: true, trigger: 'blur', validator: validatorNickName },
  ],
  password: [
    { required: true, trigger: 'blur', validator: validatorPassword }
  ]
})


let userParam = reactive<UserVO>({
  id: 0,
  username: '',
  nickname: '',
  password: '',
})

// 取消按钮
let cancelClick = () => {
  // 关闭抽屉
  drawer.value = false;
};
// 添加用户
let handlerAddUser = async () => {
  // 清空 用户信息
  Object.assign(userParam, {
    id: null,
    username: '',
    nickname: '',
    password: '',
  })
  // 清除上次提示的错误信息
  nextTick(() => {
    // 清空表单
    formRef.value.cleanValidate('username');
    formRef.value.cleanValidate('password');
    formRef.value.cleanValidate('nickname');
  })
  // 添加用户 抽屉打开
  drawer.value = true;
}

const handlerDelete = async (row: UserVO) => {
  let ids: number[] = [row.id as number];
  delBatchUserByIds(ids)
  // 把该用户的id从userIds中排除出来
  userIds.value = userIds.value.filter(item => item !== row.id)
};


const delBatchUserByIds = async (ids: number[]) => {
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  let removeResult = await reqRemoveUserByIds(ids);
  if (removeResult.code != 200) {
    ElMessage.success(removeResult.message);
    return
  }
  ElMessage.success('删除成功');
  userIds.value = [];
  handlerUserList();
}
const handlerBatchDelete = async () => {
  if (userIds.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  delBatchUserByIds(userIds.value);
  ElMessage.success('删除成功');
  userIds.value = [];
  handlerUserList(userAttr.value.length > 1 ? pageIndex.value : pageIndex.value - 1);
};
const handlerEdit = async (row: UserVO) => {
  Object.assign(userParam, row);
  drawer.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });

};

const handlerDispatcherRole = async (row: UserVO) => {
  Object.assign(userParam, row);
  let roleInfoResult: Response<RoleInfoVO> = await reqGetUserRoleAndAllRoleList(row.id as number);
  if (roleInfoResult.code != 200) {
    ElMessage.error(roleInfoResult.message);
    return;
  }
  let roleInfo: RoleInfoVO = roleInfoResult.data ?? {};
  allRoles.value = roleInfo.allRoles ? roleInfo.allRoles : [];
  checkedRoleIds.value = (roleInfo.assignedRoles ? roleInfo.assignedRoles : [])
    .map((item: UserRole) => item.id)
    .filter((id): id is number => id !== undefined);
  roleDrawer.value = true;
};

const handlerSaveOrUpdateUser = async () => {
  // 点击保存按钮的时候务必确保表单数据是正确的
  await formRef.value.validate();

  let saveOrUpdateUserResult = await reqSaveOrUpdateUser(userParam);
  if (saveOrUpdateUserResult.code != 200) {
    ElMessage.error(saveOrUpdateUserResult.message);
    return;
  }
  ElMessage.success(userParam.id ? '修改成功' : '保存成功');
  // 此行可留可不留
  // handlerUserList(userParam.id ? pageIndex.value : 1);
  // 自动刷新浏览器
  window.location.reload();
  drawer.value = false;
};
const handlerSearch = async () => {
  pageIndex.value = 1;
  let userListResult = await reqUserListByUserName(pageIndex.value, pageSize.value, userName.value);
  if (userListResult.code != 200) {
    ElMessage.error(userListResult.message);
    return;
  }
  let pvo = userListResult.data;
  userAttr.value = pvo?.list || []
  total.value = pvo?.total || 0
}
const handleSizeChange = () => {
  // console.log(`每页 ${limit} 条`);
  // pageSize.value = limit;
  handlerUserList();
};
const handlerUserList = async (page = 1) => {
  pageIndex.value = page;
  if (!userName.value) {
    let userListResult = await reqUserList(pageIndex.value, pageSize.value);
    if (userListResult.code !== 200) {
      ElMessage.error(userListResult.message);
      return;
    }
    let pvo = userListResult.data;
    userAttr.value = pvo?.list || [];
    total.value = pvo?.total || 0;
  } else {
    let userListResult = await reqUserListByUserName(pageIndex.value, pageSize.value, userName.value);
    if (userListResult.code !== 200) {
      ElMessage.error(userListResult.message);
      return;
    }
    let pvo = userListResult.data;
    userAttr.value = pvo?.list || [];
    total.value = pvo?.total || 0;
  }


}


onMounted(() => {
  // 组件被加载后 请求后端
  handlerUserList()
});


</script>

<style scoped lang="scss">
.form {
  display: flex; // 飘起来
  justify-content: space-between; // 一左一右
  align-items: center;
}
</style>